//
//  RadioButton.swift
//  MikerShop
//
//  Created by eme on 2016/12/25.
//  Copyright © 2016年 eme. All rights reserved.
//

import Foundation
import SnapKit
import RxSwift

class RadioButton: UIView {
    
    ///关
    private var offBtn:UIButton = UIButton()
    /// 开
    private var onBtn:UIButton = UIButton()
    
    
    let radioSubject = PublishSubject<String>()
    
    var radioState:String?{
        didSet{
            if let radioState = self.radioState, radioState == "1" {
                self.offBtn.isSelected = false
                self.onBtn.isSelected = true
            }else{
                self.offBtn.isSelected = true
                self.onBtn.isSelected = false
            }
        }
    }
    
    
    private let disposeBag = DisposeBag()
    override func awakeFromNib() {
        setupSubviews()
    }
    
    func setupSubviews() {
        
        
        offBtn.setTitle("否", for: .normal)
        offBtn.setImage(UIImage(named: "radio-unselected", in: AryaCore.bundle, compatibleWith: nil), for: .normal)
        offBtn.setImage(UIImage(named: "radio-selected", in: AryaCore.bundle, compatibleWith: nil), for: .selected)
        offBtn.setTitleColor(UIColor.black, for: .normal)
        self.addSubview(offBtn)
        
        onBtn.setTitle("是", for: .normal)
        onBtn.setTitleColor(UIColor.black, for: .normal)
        onBtn.setImage(UIImage(named: "radio-unselected", in: AryaCore.bundle, compatibleWith: nil), for: .normal)
        onBtn.setImage(UIImage(named: "radio-selected", in: AryaCore.bundle, compatibleWith: nil), for: .selected)
        self.addSubview(onBtn)
        
        offBtn.snp.makeConstraints{ make in
            make.centerY.equalToSuperview()
            make.leading.equalTo(0)
            make.top.equalTo(0)
        }
        onBtn.snp.makeConstraints{ make in
            make.leading.equalTo(self.offBtn.snp.trailing).offset(0)
            make.centerY.equalToSuperview()
            make.trailing.equalTo(0)
            make.top.equalTo(0)
            make.width.equalTo(self.offBtn.snp.width)
        }
        self.offBtn
            .rx.tap
            .subscribe(onNext: { [unowned self] ( _ ) in
                self.onBtn.isSelected = false
                self.offBtn.isSelected = true
                self.radioSubject.onNext("0")
            })
            .disposed(by: disposeBag)
        self.onBtn
            .rx.tap
            .subscribe(onNext: { [unowned self] ( _ ) in
                self.radioSubject.onNext("1")
                self.onBtn.isSelected = true
                self.offBtn.isSelected = false
            })
            .disposed(by: disposeBag)
    }
    
}
